<template>
  <a-modal
    v-model:visible="modalVisible"
    width="1200px"
    :hide-cancel="true"
    :mask-closable="false"
    :hide-ok="true"
    @ok="CreateOrder"
    @cancel="handleCancel"
    ok-text="创建采购订单"
  >
    <template #title> 明细列表 </template>
    <div>
      <a-table
        :columns="columns"
        :data="data"
        :pagination="false"
        v-bind="args ? { ...args } : null"
      >
        <template #columns>
          <a-table-column
            v-for="item in columns"
            :title="item.title"
            :data-index="item.code"
            :key="item.code"
            :width="200"
            align="center"
          >
            <!-- 数量 -->
            <template v-if="item.code === 'amount'" #cell="{ record }">
              <a-input-number
                :min="1"
                @change="amountChange(record)"
                placeholder="请输入销售数量"
                :disabled="record.amount"
                v-model="record.amount"
                hide-button
              />
            </template>
            <!-- 供应商名称 -->
            <template v-else-if="item.code === 'SupplierId'" #cell="{ record }">
              <a-input
                v-model="record.supplierName"
                hide-button
                @click="SelectSup(record.number)"
              />
            </template>
            <!-- 指导单价 -->
            <template v-else-if="item.code === 'guidePrice'" #cell="{ record }">
              <a-input-group>
                <a-input-number
                  :min="1"
                  @change="saleMoneyChange(record)"
                  v-model="record.guidePrice"
                  :disabled="record.guidePrice"
                  hide-button
                />
                <a-select
                  default-value="人民币"
                  v-model="record.guidePriceUnit"
                  :disabled="record.guidePriceUnit"
                  :options="['人民币', '美元', '港币']"
                />
              </a-input-group>
            </template>
            <!-- 折扣 -->
            <template v-else-if="item.code === 'discount'" #cell="{ record }">
              <a-input-number
                :min="0"
                hide-button
                v-model="record.discount"
                @change="cgeDiscount(record)"
              >
                <template #append> % </template>
              </a-input-number>
            </template>
            <!-- 合计 -->
            <template v-else-if="item.code === 'total'" #cell="{ record }">
              <a-input-group>
                <a-input disabled v-model="record.totalPrice" />
                <a-select
                  default-value="人民币"
                  disabled
                  v-model="record.guidePriceUnit"
                  :options="['人民币', '美元', '港币']"
                />
              </a-input-group>
            </template>
          </a-table-column>
          <!-- <a-table-column
            :width="200"
            fixed="right"
            title="操作"
            align="center"
          >
            <template #title> 操作 </template>
            <template #cell="{ record }">
              <div>
                <a-button type="text" @click="CreateOrder(record)"
                  >创建采购订单</a-button
                >
              </div>
            </template>
          </a-table-column> -->
        </template>
      </a-table>
    </div>
  </a-modal>
  <SelectSupplier
    ref="SelectSupplierRef"
    v-model:visible="SuppliermodalVisible"
    :code="supplierNumber"
    @awardedSupplier="awardedSupplier"
  />
</template>

<script lang="ts" setup>
  import { cloneDeep } from 'lodash';
  import { nextTick, computed, watchEffect, onMounted, ref } from 'vue';
  import { localGetUserInfo } from '@/utils/localStorage/account';
  import { getPurchaseProductNumber } from '@/api/buy-management/buy-material/index';
  import { useRouter } from 'vue-router';
  import { useBuyStore } from '@/store';
  import Message from '@arco-design/web-vue/es/message';
  import SelectSupplier from '../select-supplier/index.vue';

  const store = useBuyStore();
  const router = useRouter();
  const SuppliermodalVisible = ref(false);
  const SelectSupplierRef = ref();
  const props = withDefaults(
    defineProps<{
      SeeDate: any;
      visible: boolean;
    }>(),
    {
      visible: false,
    }
  );
  const args = {
    bordered: {
      headerCell: true,
    },
    stripe: true,
  };
  const columns = [
    {
      title: '物料编码',
      code: 'number',
    },
    {
      title: '物料名称',
      code: 'name',
    },
    {
      title: '型号规格',
      code: 'spec',
    },
    {
      title: '基本单位',
      code: 'basicName',
    },
    {
      title: '需求数量',
      code: 'amount',
    },
    {
      title: '关联申请单号',
      code: 'applyNumber',
    },
    {
      title: '供应商名称',
      code: 'SupplierId',
    },
    {
      title: '产品指导单价',
      code: 'guidePrice',
    },
    {
      title: '折扣',
      code: 'discount',
    },
    {
      title: '合计',
      code: 'total',
    },
  ];

  const emit = defineEmits(['update:visible', 'addRoleEmit']);

  // 判断用户是否显示弹出框
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  // const data = ref([]);

  // const getData = () => {
  //   data.value = props.SeeDate;
  //   data.value.forEach(async (item: any) => {
  //     const res = await getPurchaseProductNumber({ number: item.number });
  //     let markSupplier = res.filter((i: any) => i.mark === 1);
  //     markSupplier = markSupplier.length > 0 ? markSupplier : res;
  //     item.supplierName = markSupplier[0].supplierName;
  //     item.supplierId = markSupplier[0].supplierId;
  //     item.guidePrice = markSupplier[0].singlePrice;
  //     item.totalPrice = markSupplier[0].singlePrice * item.amount;
  //     item.guidePriceUnit = '人民币';
  //   });
  // };

  // getData();

  // const amountChange = (record: any) => {
  //   if (record.guidePrice !== undefined && record.amount !== undefined) {
  //     record.totalPrice = record.guidePrice * record.amount;
  //     record.discount = 0;
  //   } else record.totalPrice = 0;
  // };

  // // 修改销售单价价格
  // const saleMoneyChange = (record: any) => {
  //   if (record.guidePrice !== undefined && record.amount !== undefined) {
  //     record.totalPrice = record.guidePrice * record.amount;
  //     record.discount = 0;
  //   } else record.totalPrice = 0;
  // };

  const supplierNumber = ref();
  const SelectSup = (code: string) => {
    supplierNumber.value = code;
    SuppliermodalVisible.value = true;
  };

  const supplierId = ref();

  // const awardedSupplier = (tatleDate: any) => {
  //   const firstItem = tatleDate[0];
  //   supplierId.value = firstItem.supplierId;
  //   data.value = data.value.map((i: any, index: number) => {
  //     return {
  //       ...i,
  //       supplierName: firstItem.supplierName,
  //       supplierId: firstItem.supplierId,
  //       guidePrice: firstItem.singlePrice,
  //       discount: firstItem.discount ? firstItem.discount : 0,
  //       totalPrice: firstItem.singlePrice * i.amount,
  //       guidePriceUnit: '人民币',
  //     };
  //   });
  // };

  const cgeDiscount = (record: any) => {
    // saleMoneyChange(record);
    if (record.discount) {
      let msg = ref(0);
      record.totalPrice = record.guidePrice * record.amount;
      msg.value = (100 - record.discount) / 100;
      record.totalPrice *= msg.value;
    }
  };

  // const CreateOrder = (record?: any) => {
  //   const { supplierId, supplierName, totalPrice } = data.value[0];
  //   if (supplierId) {
  //     data.value[0].sourceProductId = data.value[0].id;
  //     data.value[0].sid = data.value[0].id;

  //     // record.sourceProductId = record.id;
  //     // record.sid = `${record.id}`;
  //     store.CreateOrder = {
  //       supplierId,
  //       supplierName,
  //       totalPrice,
  //       Product: [{ ...data.value[0] }],
  //     };
  //     router.push({
  //       name: 'AddOrderPurchaseList',
  //     });
  //   } else {
  //     Message.error('请选择供应商');
  //   }
  // };

  // watchEffect(() => {
  //   // nextTick(() => {
  //   getData();
  //   // });
  // });

  const handleCancel = () => {
    SelectSupplierRef.value.Refresh();
    modalVisible.value = false;
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
    // font-size: 13px;
  }
</style>
